package top.lyc829.mymusic.model.repository

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import top.lyc829.mymusic.model.db.BannerDao
import top.lyc829.mymusic.model.http.AppException
import top.lyc829.mymusic.util.Const
import top.lyc829.mymusic.model.http.Error
import top.lyc829.mymusic.model.http.MyNetwork
import java.lang.RuntimeException

/**
 * @Author lyc
 * @create 2021-07-06 13:31
 */
class IndexRepository private constructor(private val bannerDao: BannerDao, private val network : MyNetwork) {

    suspend fun getBannerList() = withContext(Dispatchers.IO) {
        val banner = network.getBanners(1)
        if (banner.code != Const.SUCCESS) {
            throw AppException(banner.code, "获取轮播图失败")
        }
        val list = banner.banners
        list
    }

    suspend fun getRecommendPlayList() = withContext(Dispatchers.IO) {
        val result = network.getIndexRecommendPlayList()
        if (result.code != Const.SUCCESS) {
            throw AppException(result.code, "获取歌单失败")
        }
        result.recommend.take(6)
    }

    suspend fun getTopAlbums() = withContext(Dispatchers.IO) {
        val result = network.getTopAlbums()
        if (result.code != Const.SUCCESS) {
            throw AppException(result.code, "获取新专辑失败")
        }
        result.weekData.take(3)
    }

    suspend fun getNewSongs() = withContext(Dispatchers.IO) {
        val result = network.getNewSongs()
        if (result.code != Const.SUCCESS) {
            throw AppException(result.code, "获取新歌失败")
        }
        result.data.take(3)
    }

    suspend fun search(keyword : String) = withContext(Dispatchers.IO) {
        val search = network.search(keyword)
        search
    }

    companion object {
        private var instance: IndexRepository? = null
        fun getInstance(bannerDao: BannerDao, network: MyNetwork): IndexRepository {
            if (instance == null) {
                synchronized(IndexRepository::class.java) {
                    if (instance == null) {
                        instance = IndexRepository(bannerDao, network)
                    }
                }
            }
            return instance!!
        }
    }
}